package gre.core;

import gre.db.*;
import java.io.*;
import java.sql.*;
import java.util.*;

/**
 *
 * @author nacuong
 */
public class AutoBackup {
  static public final String backupFile = "wordsBK.txt";

  /**
   * Store data in the database into the backup file.
   * The data are appended in the end of file.
   *
   * @param stmt
   * @throws SQLException
   * @throws IOException
   */
  public static void storeData(Statement stmt) throws SQLException, IOException{
    ResultSet results = stmt.executeQuery("SELECT wid FROM words");
    Vector<Integer> wordIds = new Vector<Integer>();
    while (results.next()){
      wordIds.add(results.getInt("wid"));
    }

    for (int wordId: wordIds){
      String word = DBSelector.selectWord(stmt, wordId);
      String meaning = DBSelector.selectMeaning(stmt, wordId);
      Vector<String> sentences = DBSelector.selectStatement(stmt, wordId);
      String data = word + "|" + meaning + "|";
      for (int inx = 0; inx < sentences.size(); inx++){
        data += sentences.get(inx);
        if (inx < sentences.size()-1) data +="@";
      }
      appendData(data);
    }
  }

  /**
   * Append a data string word|meaning|sentences into the end of backup file.
   * 
   * @param data
   * @throws IOException
   */
  public static void appendData(String data) throws IOException{
    File file = new File(DBHelper.getCurrentPath() + AutoBackup.backupFile);
    file.createNewFile();
    PrintWriter writer = new PrintWriter(new FileWriter(file, true));
    writer.println(data);
    writer.close();
  }
}
